<?php
class tools{
	
	/**
	 * prepare value before execiute
	 *
	 * @param String $__v		// value to save in table
	 * @param Bool $__q			// width quite or not
	 * @param String $__d		// type of database
	 * @return String
	 */
	public static function __mres($__v,$clear=false,$__q=false,$__d=null){
		global $parameters;
		if($clear) $__v = tools::Html2Clean($__v);
		$__d =  (is_null($__d)) ? $parameters['drivers']['driver'] : $__d;
		$__v = str_replace("'", "\'", $__v);
		switch($__d){
			case "mysql":
				if (!$__q){
					return "'".mysql_escape_string("$__v")."'";
				}else{
					if(!empty($__v)) 
						return mysql_escape_string("$__v");
				}
				break;
			case "sqlite":
				if (!$__q){
					return "'".sqlite_escape_string("{$__v}")."'";
				}else{
					if(!empty($__v)) 
						return sqlite_escape_string("{$__v}");
				}				
		}
	}
	
	/**
	 * nakładka na PDO
	 * 
	 * @param $__f			pdo function
	 * @param $__q			query string
	 * @param $__debug		debuger
	 * @param $__db			obiekt polaczenia z baza
	 * @param $__drive		typ bazy
	 * @return array
	 */
	public static function __adodb($__f='',$__q='',$__debug=true,$__db=null,$__drive=null){
		global $dbl,$parameters;
		$timestart = microtime();
		$__drive =  (is_null($__drive)) ? $parameters['drivers']['driver'] : $__drive;
		if (is_object($dbl) && is_null($__db) ){
			$__db = $dbl;
		}
	
		if ( is_string($__f) && is_string($__q) && !empty($__q) ){
			try{
				switch ($__f){
					case 'getAll':
						$__w = $__db->query($__q)->fetchAll();
						break;
					case 'getRow':
						$__w =  $__db->query($__q)->fetch();
						break;
					case 'getOne':
						$sth = $__db->prepare($__q);
						$sth->execute();
						$__w = $sth->fetch(PDO::FETCH_BOTH);
						$__w = $__w[0];
						break;
					case 'getCol':
						//$__w = $__db->query($__q)->fetchColumn();
						 try {
				            $stmt = $__db->query($__q);
				            $__w = $stmt->fetchAll(PDO::FETCH_COLUMN);
				        } catch (PDOException $e) {
				           // $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
//				                array(
//				                    'container' => 'could not fetch single column: ' . $e->getMessage(),
//				                    'debug'     => $e->getTrace()
//				                )
//				            );
				            $__w = null;
				        }
						
						break;	
					case 'conCol':
						$__w = $__db->query($__q)->columnCount();
						break;				
					case 'getAssoc':
						$__w = tools::GetAssoc($__q,null,$__db);
						break;
					case 'exec':
						$sth = $__db->prepare($__q);
						$__w = $sth->execute();
						break;
				}
				if ($parameters['sqlite']['debugging'] ){	
					if (!is_null($__debug)){
						$timeend = microtime();
						$time = tools::differencesBetweenTwoTimes($timestart,$timeend);
						config::debug_query($__q,1,$__drive,$time);	
						$error = $__db->errorInfo();
					  	if($error[0] != "00000") {
							config::debug_query(print_r($error,true).' '.$__q,1,$__drive,$time);
						}
					}
				}
				unset($__db);
				if(is_array($__w)) return tools::stripslashes_array($__w); 
				return $__w ;	
			}catch (PDOException $e) {	
				if (!is_null($__debug)){
					return config::debug_query($e->getMessage()." in query = [ {$__q} ]",1,$__drive);
				}
			} 
			
			
		}else{
			return false;
		}
	}
	
	public static function differencesBetweenTwoTimes($firstTime,$lastTime){
		$startarray = explode(" ", $firstTime);
		$starttime = $startarray[1] + $startarray[0];
		
		$endarray = explode(" ", $lastTime);
		$endtime = $endarray[1] + $endarray[0];
		$totaltime = $endtime - $starttime; 
		$totaltime = round($totaltime,5);
		return $totaltime;
	}

	public static function GetAssoc($sql, $vars=null,$__db) { 
		$out = array(); 
		$st = tools::DoQuery($sql, $vars,$__db); 
		if($st) {
			$_col = $st->columnCount() ;
			if($_col > 2) { 
				while($row = $st->fetch()) { 
					$rowidx = array_shift($row); 
					$out[$rowidx] = $row; 
				} 
			}  else { $out = false; }
			if($_col == 2) { 
				
				while($row = $st->fetch()) { 
					$rowidx = array_shift($row); 
					$out[$rowidx] = array_shift($row); 
				} 
				
			} else { $out = false; }
		} else { $out = false; }		
		return $out; 
	}
	
	public static function DoQuery($sql, $vars=null,$__db) {
		$st = $__db->prepare($sql);
		$st->setFetchMode(PDO::FETCH_ASSOC);
		return $st->execute()?$st:false; 
	} 
	
	/**
	 * zlicza wynik zapytania Sqlect
	 *
	 * @param arr $__w
	 * @return num
	 */
	public static function __count_row($__w=null){
		if (!is_array($__w)) return 0;
		$__count = 0;
		foreach( $__w as $k ) {
		    $__count++;
		}
		return $__count;
	}
	
	public static function _assign($smartyName,$SmartyData=''){
		global $smarty;
		if ( is_string($smartyName) && strlen($smartyName) > 0 ) $smarty->assign($smartyName,$SmartyData);
	}
	public static function _fetch($SmartyTpl=''){
		global $smarty;
		if ( $smarty->template_exists($SmartyTpl) ) return $smarty->fetch($SmartyTpl);
		return false;
	}
	public static function _display($SmartyTpl='',$cache_id=null,$compile_id = null){
		global $smarty;
		if ( $smarty->template_exists($SmartyTpl) ) $smarty->display($SmartyTpl,$cache_id,$compile_id);
		return false;
	}
	
	/**
	 * conwert url
	 *
	 * @param Str $link
	 * @param Str $podmien
	 * @param Str $uwzglednij
	 * @return Str
	 */
	public static function __link($link,$podmien="-",$uwzglednij="[^0-9A-Za-z\!\.#_-]"){
		$znaki = array("ó","ł","ń","ć","ź","ż","ą","ś","ę","Ó","Ł","Ń","Ć","Ź","Ż","Ą","Ś","Ę");
		$znakx = array("o","l","n","c","z","z","a","s","e","O","L","N","C","Z","Z","A","S","E");
		$link = str_ireplace($znaki,$znakx,$link);
		$link = strtr($link,'/ABCDEFGHIJKLMNOPRSTWZXY:','-abcdefghijklmnoprstwzxy-');
		//$link = urlencode($link);
		return strtolower(preg_replace("/{$uwzglednij}/",$podmien,$link));
	}
	
	/**
	 * convert xml to array
	 *
	 * @param xml $xml
	 * @return Array
	 */
	public static function xml2assoc(&$xml) {
      $assoc = null;
      while($xml->read()){
        switch ($xml->nodeType) {
          case XMLReader::END_ELEMENT: return $assoc;
          case XMLReader::ELEMENT:
            $assoc[$xml->name][] = array('value' => $xml->isEmptyElement ? '' : tools::xml2assoc($xml));
            if($xml->hasAttributes){
              $el =& $assoc[$xml->name][count($assoc[$xml->name]) - 1];
              while($xml->moveToNextAttribute()) $el['attributes'][$xml->name] = $xml->value;
            }
            break;
          case XMLReader::TEXT:
          case XMLReader::CDATA: $assoc .= $xml->value;
        }
      }
      return $assoc;
	}

	/**
	 * return array with folders and files names
	 * for selected root folder
	 *
	 * @param String $target
	 * @param Bool $debaging
	 * @return Array
	 */
	public static function get_folders_files($target,$debaging=true){
		global $arr,$j;
		if (empty($j)) $j = 0;
		$files= array();
		$exceptions=array('.','..');
		if (!$sourcedir=@opendir($target)){
			if ($debaging)
				echo 'blad otwarcia folderu '.$target."<br />\n";
				return false;
			}
			$i=0;
			while(false!==($sibling=readdir($sourcedir))){
				if(!in_array($sibling,$exceptions)){
					$object=str_replace('//','/',$target.'/'.$sibling);
					if(is_dir($object)){
						tools::get_folders_files($object);
						$files[$i]= $object;
					}
					if(is_file($object)){
						$files[$i]['nazwa'] = $object;
					}
					$i++;
				}
			}
			closedir($sourcedir);
			$arr[$j] = array('folder'=>$target,'files'=> $files) ;
			$j++;
			return $arr;
	}

	public static function get_files($target, $arr=null,$j=0,$debaging=true){
		
		if (is_null($arr)) $arr = '';
		$files= array();
		$exceptions=array('.','..');
		if (!$sourcedir=@opendir($target)){
			if ($debaging)
				echo 'blad otwarcia folderu '.$target."<br />\n";
				return false;
			}
			$i=0;
			while(false!==($sibling=readdir($sourcedir))){
				if(!in_array($sibling,$exceptions)){
					$object=str_replace('//','/',$target.'/'.$sibling);
					if(is_dir($object)){
						$arr = tools::get_files($object,$arr,$j++) ;
						$files[$i]= $object;						
					}
					if(is_file($object)){
						$files[$i]['nazwa'] = $object;
					}
					$i++;
				}
			}
			closedir($sourcedir);
			$arr[$j] = array('folder'=>$target,'files'=> $files) ;
			$j++;
			return $arr;
	}
	

	/**
	 * delete selected file
	 *
	 * @param String $__file
	 * @return array
	 */	
	public static function _delete_file($__file){
		try {
			$ret = array();
			if(file_exists($__file)){
				$result = @unlink($__file);
				$ret[0] = $result;
				$ret[1] = 'file '.$__file. ' deleted.';
			}else{
				$ret[0] = false;
				$ret[1] = 'Error: file '.$__file. ' not exists.';
			}
			return $ret;
		}catch ( Exception  $e ){
			$ret[0] = false;
			$ret[1] = $e->getMessage();	
			return $ret;		
		}
	}
	
	/**
	 * upload file from tmp file on serwer
	 *
	 * @param Number $id_user
	 * @param Number $id_albumu
	 * @param String $sciezka
	 * @return Array
	 */
	public static function file_uploader($name=null,$pref=null,$path=null){
		$max_wielkosc_pliku = 1048576 * 1; // 1MB = 1048576;
		$pliki = array();
		foreach ($_FILES as $fieldName => $file) {
			if ($_FILES['Filedata']['size'] <= $max_wielkosc_pliku) {
				$fiSize = $_FILES['Filedata']['size'];
				$fiExte = tools::__rozszrzenie_pliku($file['name']);
				$fiName = strtolower($pref.tools::_przyjazny_link(((is_null($name))?$file['name']:$name)));
				$up=move_uploaded_file($file['tmp_name'], /*"./".*/ $pref . $fiName );
				array_push($pliki,$fiName);
			}else{
				$up = false;
			}
		}
		return $pliki;
	}
	
	/**
	 * add folders for path
	 *
	 * @param String $__folder_path
	 * @param String $__atribs
	 */
	public static function _add_folder($__folder_path,$__atribs = '0755'){
		$__arr_path = explode('/',$__folder_path);
		$__path_progress = '';
		foreach ($__arr_path as $__folder) {
			$__path_progress .= $__folder;
			if(!is_dir( $__path_progress )) {
				@mkdir( $__path_progress );
				@chmod( $__path_progress.'/' ,0777);
			}else{
				@chmod( $__path_progress.'/' ,0777);
			}
			$__path_progress .= '/';
		}		
	}
	
	/**
	 * sprawdza czy folder istnieje
	 * @param $dir_name
	 * @param $path
	 * @return unknown_type
	 */
	public static function _dir_exists($dir_name = false, $path = './') {
	    if(!$dir_name) return false;
	    
	    if(is_dir($path.$dir_name)) return true;
	    
	    $tree = glob($path.'*', GLOB_ONLYDIR);
	    if($tree && count($tree)>0) {
	        foreach($tree as $dir)
	            if(tools::_dir_exists($dir_name, $dir.'/'))
	                return true;
	    }
	    
	    return false;
	}

	public static function _redirect($__url="/",$__message="Proszę się zalogować...",$sekundy = 2,$typ="js"){
		switch($typ){
			case 'js':
				$__redirect['url'] = $__url;
				$__redirect['message'] = $__message;
				$__redirect['odliczanie '] = $sekundy;
				tools::_assign('redirect',$__redirect);
				tools::_display("section/const_redirect.tpl");
				break;
			case 'php':
				header("Location: ".HTTP_URL.$__url);
				
		}
	}
	
	public static function stripslashes_array($value) {
        $value = is_array($value) ? array_map(array("tools", "stripslashes_array"), $value) : stripslashes($value);
        return $value;
    }
    
	private function _dodaj_pliki_do_wiadomosci_email(){
		$this->arrPliki = Array(
	  		Array("file"=>"../../test.doc", "content_type"=>"application/msword"),
	  		Array("file"=>"../../123.pdf", "content_type"=>"application/pdf")
  		);	
	}
	
	private static function __generuj_email($nadawca,$adres_nadawcy,$odbiorca,$temat,$tresc,$wersja){
                $eol="\r\n";
                $mime_boundary=md5(time());
                $attachments=false;
                $msg = "";
                $headers ="";
                
                # Common Headers
                $headers .= 'From: '.$nadawca.' <'.$adres_nadawcy.'>'.$eol;
                $headers .= 'Reply-To: '.$nadawca.' <'.$adres_nadawcy.'>'.$eol;
                //$headers .= 'Return-Path: '.$nadawca.' <'.$adres_nadawcy.'>'.$eol;    // these two to set reply address
                $headers .= "Message-ID: <".date('Y.m.d H:i:s')." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
                //$headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters


        
                # Boundry for marking the split & Multitype Headers
                //$headers .= 'MIME-Version: 1.0'.$eol;
                //$headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
                
                     
                
                if ($attachments !== false){
                        for($i=0; $i < count($attachments); $i++){
                                if (is_file($attachments[$i]["file"])){ 
                                        # File for Attachment
                                        $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
                                        $handle=fopen($attachments[$i]["file"], 'rb');
                                        $f_contents=fread($handle, filesize($attachments[$i]["file"]));
                                        $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
                                        fclose($handle);
                                        # Attachment
                                        $msg .= "--".$mime_boundary.$eol;
                                        $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;
                                        $msg .= "Content-Transfer-Encoding: base64".$eol;
                                        $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
                                        $msg .= $f_contents.$eol.$eol;
                                }
                        }
                }
                
                # Setup for text OR html
                //$msg .= "Content-Type: multipart/alternative".$eol;
                # Text
                if ($wersja == 'txt'){
                        //$msg .= "--".$mime_boundary.$eol;
                        //$msg .= "Content-Type: text/plain; charset=iso-8859-2".$eol;
                        //$msg .= "Content-Transfer-Encoding: 8bit".$eol;
                        $msg .= strip_tags(str_replace("<br>", "\n", $tresc)).$eol.$eol;
                }
                # HTML
                if ($wersja == 'htm'){
                        $msg .= "--".$mime_boundary.$eol;
                        $msg .= "Content-Type: text/html; charset=iso-8859-2".$eol;
                        $msg .= "Content-Transfer-Encoding: 8bit".$eol;
                        $msg .= $eol.$eol.$eol.$tresc.$eol.$eol;
                        $msg .= "--".$mime_boundary."--".$eol.$eol;
                }


                ini_set('sendmail_from',$adres_nadawcy);
                $ret = mail($odbiorca,$temat, $msg, $headers);
                ini_restore('sendmail_from');
                return $ret;

	}

	/**
	 * wysyła wiadomosć 
	 *
	 * @param String $nadawca
	 * @param String $adres_nadawcy
	 * @param String $odbiorca
	 * @param String $temat
	 * @param String $tresc
	 * @param String $wersja
	 * @return Bool
	 */
	public static function __wiadomosc($nadawca="",$adres_nadawcy="",$odbiorca="",$temat="",$tresc="",$wersja="htm",$chackemail = true){
		if ($chackemail){ if (!tools::__email($adres_nadawcy)) return false; }
		$odbiorca = tools::_utf82iso($odbiorca);
		$nadawca = tools::_utf82iso(str_replace(","," ",$nadawca));
		$temat = tools::_utf82iso($temat);
		$tresc = tools::_utf82iso($tresc);
		if ( tools::__generuj_email($nadawca,$adres_nadawcy,$odbiorca,$temat,$tresc,$wersja) ){
			return true;			
		}else{
			return false;		
		}

	}
	
	public static function _utf82iso($AStr){
		return iconv('UTF-8', 'ISO-8859-2', $AStr);
	}
	public static function _utf2cp1250($string){
		return iconv('UTF-8', 'cp1250', $string);
	}
	public static function __email($email){
		$filtr ="/^[a-z]+[a-z0-9]*[\.|\-|_]?[a-z0-9]+@([a-z0-9]+)\.[a-z0-9]{2,4}$/";
		return (preg_match($filtr,$email)) ? true : false ;
	}
	
	public static function __rozszrzenie_pliku($nazwa)
	{	
		$nazwa = strtolower($nazwa) ;
		$exts = split("[/\\.]", $nazwa) ;
		$n = count($exts)-1;
		$exts = $exts[$n];
		return $exts;
	}
	
	public static function Html2Clean($document){
		$document = stripslashes($document);
		$junk = 'style|STYLE|class|CLASS|align|ALIGN';
		$search = array('@<script[^>]*?'.'>.*?</script>@si',  // Strip out javascript
					'@<style[^>]*?'.'>.*?</style>@siU',    // Strip style tags properly
					'@<![\s\S]*?--[ \t\n\r]*>@'       // Strip multi-line comments including CDATA
					//'/([\s]+)('.$junk.')([\s]*)=([\s]*)(("|\’)([^"\']+)("|\’)|([^>"\']+))*/' // atrybuty style|STYLE|class|CLASS|align|ALIGN
				);
		$text = preg_replace($search, '', $document);
		return $text;
	}
	
	public static function Html2Text($document){
		$document = stripslashes($document);
		$junk = 'style|STYLE|class|CLASS|align|ALIGN';
		$search = array('@<script[^>]*?'.'>.*?</script>@si',  // Strip out javascript
					'@<style[^>]*?'.'>.*?</style>@siU',    // Strip style tags properly
					//'@<[\/\!]*?[^<>]*?'.'>@si',            // Strip out HTML tags
					'@<![\s\S]*?--[ \t\n\r]*>@'       // Strip multi-line comments including CDATA
					//'/([\s]+)('.$junk.')([\s]*)=([\s]*)(("|\’)([^"\']+)("|\’)|([^>"\']+))*/' // atrybuty style|STYLE|class|CLASS|align|ALIGN
				);			
		$text = preg_replace($search, '', $document);
		return $text;
	}	
	
	public static function przygotujTxtDlaXML($htmlStr){ 
		$xmlStr=str_replace('<','&lt;',$htmlStr); 
		$xmlStr=str_replace('>','&gt;',$xmlStr); 
		$xmlStr=str_replace('"','&quot;',$xmlStr); 
		$xmlStr=str_replace("'",'&#39;',$xmlStr); 
		$xmlStr=str_replace("&",'&amp;',$xmlStr); 
		return $xmlStr; 
	}
	
	public static function _stronicowanie($query=0,$strona=1/*strona docelowa*/,$ins=10/*ilosc na strone*/,$zakres=2,$prefix__ = ''){
		if ( $strona > ceil( $query / $ins) or $strona <= 0 ) $strona = 1;
		// zacznij od rekordu
		$zor = $strona * $ins - $ins;	
		// ilosc stron
		$j = ceil( $query / $ins);
		$min = 0;	
		$max = 0;	
		
		// wyswietlamy strony od $i
		$i = $strona - $zakres;
		$ui = 0; // uzupełnienie dla $k
		if ($i < $zakres && $i <= 0){
			$ui = $zakres - $i -1;
			$i = 1;
			$min = 0;
		}else{
			$min = 1;
		}
		// wyswietlamy strony do $k
		$k = $strona + $zakres + $ui;
		if ( $k > $j-1 ){
			if ($i > ($k-$j) )	$i = $i - ($k-$j);
			$k = $j;
			$max = 0 ;			
		}else{			
			$max = $j;
		}		
		$apages = array();	
		for ($i; $i<=$k;$i++) $apages[$i] = $i;
		// jesli strony nie ma w wyswietlanych sronach to ustaw na pierwszą	
		$strona = isset($apages[$strona]) ? $strona :  1;
		if ( count($apages) > 1 ) tools::_assign("{$prefix__}apages",$apages);
		tools::_assign("{$prefix__}curPage",$strona);
		tools::_assign("{$prefix__}pierwszaStrona",$min);
		tools::_assign("{$prefix__}ostatniaStrona",$max);	
		return "LIMIT ". $zor . "," . $ins;
	}
	
	public static function getUserIP(){
	    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
	    {
	      $ip=$_SERVER['HTTP_CLIENT_IP'];
	    }
	    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
	    {
	      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	    }
	    else
	    {
	      $ip=$_SERVER['REMOTE_ADDR'];
	    }
	    return $ip;
	}
	
	public static function getUserLatLng($ip){
		global $parameters;
		
		include("GeoIP/geoipcity.inc");
		include("GeoIP/geoipregionvars.php");
		$gi = geoip_open($parameters['geoip']['host'].$parameters['geoip']['database'],GEOIP_MEMORY_CACHE);
		$record = geoip_record_by_addr($gi,$ip);
		echo $record->country_code . " " . $record->country_name . "\n";
		echo $record->region . " " . $GEOIP_REGION_NAME[$record->country_code][$record->region] . "\n";
		echo $record->city . "\n";
		echo $record->postal_code . "\n";
		echo $record->latitude . "\n";
		echo $record->longitude . "\n";
		$geoip = array(	"country_code"=>$record->country_code,
				"country_code3"=>$record->country_code3,
				"country_name"=>$record->country_name,
				"region"=>$record->region . " " . $GEOIP_REGION_NAME[$record->country_code][$record->region],
				"city"=>$record->city,
				"postal_code"=>$record->postal_code,
				"latitude"=>$record->latitude,
				"longitude"=>$record->longitude
		);
		tools::_assign("geoip",$geoip);
		return $geoip;
	}	

}
